package com.ultrapower.mapper;


import java.util.Arrays;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sematext.hbase.wd.RowKeyDistributorByHashPrefix;
import com.ultrapower.buffer.Buffer;
import com.ultrapower.buffer.FixedBuffer;
import com.ultrapower.util.BytesUtils;
import com.ultrapower.util.CommonUtils;
import com.ultrapower.util.HBaseTables;
import com.ultrapower.util.topology.ResponseTime;

/**
 * @author wangy
 */
public class ResponseTimeMapper implements RowMapper<ResponseTime> {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    private RowKeyDistributorByHashPrefix rowKeyDistributorByHashPrefix;

    public ResponseTimeMapper( RowKeyDistributorByHashPrefix rowKeyDistributorByHashPrefix){
    	this.rowKeyDistributorByHashPrefix=rowKeyDistributorByHashPrefix;
    }
    @Override
    public ResponseTime mapRow(Result result, int rowNum) throws Exception {
        if (result.isEmpty()) {
            return null;
        }

        final byte[] rowKey = getOriginalKey(result.getRow());
        ResponseTime responseTime = createResponseTime(rowKey);
        for (Cell cell : result.rawCells()) {
            if (CellUtil.matchingFamily(cell, HBaseTables.MAP_STATISTICS_SELF_VER2_CF_COUNTER)) {
                recordColumn(responseTime, cell);
            }

            if (logger.isDebugEnabled()) {
                logger.debug("unknown column family:{}", Arrays.toString(CellUtil.cloneFamily(cell)));
            }
        }
        return responseTime;
    }

    void recordColumn(ResponseTime responseTime, Cell cell) {

        final byte[] qArray = cell.getQualifierArray();
        final int qOffset = cell.getQualifierOffset();
        short slotNumber = Bytes.toShort(qArray, qOffset);

        // agentId should be added as data.
        String agentId = Bytes.toString(qArray, qOffset + BytesUtils.SHORT_BYTE_LENGTH, cell.getQualifierLength() - BytesUtils.SHORT_BYTE_LENGTH);
        long count = Bytes.toLong(cell.getValueArray(), cell.getValueOffset());
        responseTime.addResponseTime(agentId, slotNumber, count);
    }

    private ResponseTime createResponseTime(byte[] rowKey) {
        final Buffer row = new FixedBuffer(rowKey);
        String applicationName = row.read2PrefixedString();
        short serviceTypeCode = row.readShort();
        final long timestamp = CommonUtils.recoveryTimeMillis(row.readLong());
        return new ResponseTime(applicationName, serviceTypeCode, timestamp);
    }

    private byte[] getOriginalKey(byte[] rowKey) {
        return rowKeyDistributorByHashPrefix.getOriginalKey(rowKey);
    }
}
